package com.example.audiostreaming.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.example.audiostreaming.Bean.IsRegisterUserAndIsPasswordBean;
import com.example.audiostreaming.Bean.UserBean;
import com.example.audiostreaming.R;
import com.example.audiostreaming.activity.LoginActivity;
import com.example.audiostreaming.base.BaseApplication;
import com.example.audiostreaming.implement.HistoryPresenter;
import com.example.audiostreaming.implement.ImplPlayerLogic;
import com.example.audiostreaming.implement.SubscriptionPresenter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UtilUser {

    private static final String TAG = "UtilUser";
    private static boolean sIsPhone;
    private static boolean sIsPassword;

    /**
     *验证登录用户输入合法性
     */
    public static boolean validateLogin(Context context, String phone, String password) throws InterruptedException {

        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(context,"手机号为空，请输入手机号",Toast.LENGTH_SHORT).show();
            return false;
        }

//        //简单的
//        RegexUtils.isMobileSimple(phone);

        //精确的
        if (!RegexUtils.isMobileExact(phone)) {
            Toast.makeText(context,"无效手机号，请输入正确手机号",Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(context,"密码为空，请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }

        userIsRegisterUserAndIsPassword(phone,password);

        if (!sIsPhone) {
            Toast.makeText(context,"当前手机号未注册",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!sIsPassword) {
            Toast.makeText(context,"密码错误",Toast.LENGTH_SHORT).show();
            return false;
        }

        //保存用户登录标记(手机号)
        boolean isSavePhone = UtilSP.saveUserPhone(context, phone);
        if (!isSavePhone) {
            Toast.makeText(context,"系统错误，请稍后重试",Toast.LENGTH_SHORT).show();
            return false;
        }

        //保存用户登录标记(密码)
        boolean isSavePassword = UtilSP.saveUserPassword(context, password);
        if (!isSavePassword) {
            Toast.makeText(context,"系统错误，请稍后重试",Toast.LENGTH_SHORT).show();
            return false;
        }

        //保存用户标记，在全局单例类之中
        UserBean.getUserBean().setTelephone(phone);
        UserBean.getUserBean().setPassword(password);

        return true;
    }

    /**
     * 退出登录
     * @param context
     */
    public static void logicOut(Context context){
        //删除sp保存的用户标记
        boolean isRemove = UtilSP.removeUser(context);
        if (!isRemove) {
            Toast.makeText(context,"系统错误，请稍后重试",Toast.LENGTH_SHORT).show();
            return;
        }

        ImplPlayerLogic instanceImplPlayerLogic = ImplPlayerLogic.getInstanceImplPlayerLogic();
        instanceImplPlayerLogic.pause();
        SubscriptionPresenter.getInstance().cleanAlbums();
        HistoryPresenter.getHistoryPresenter().cleanHistories();

        Intent intent = new Intent(context, LoginActivity.class);
        //添加intent标识符，清理task栈，并且生成一个task栈
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        //定义Activity跳转动画
        ((Activity)context).overridePendingTransition(R.anim.open_enter,R.anim.open_exit);
    }

    /**
     * 注册用户
     * @param context
     * @param phone
     * @param name
     * @param password
     * @param passwordConfirm
     */
    public static Boolean registerUser(Context context,String phone,String name,String password,String passwordConfirm) throws InterruptedException {

        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(context,"手机号为空，请输入手机号",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!RegexUtils.isMobileExact(phone)) {
            Toast.makeText(context,"无效手机号，请输入正确的手机号",Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(name)) {
            Toast.makeText(context,"昵称为空，请输入昵称",Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(context,"密码为空，请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(passwordConfirm)) {
            Toast.makeText(context,"确认密码为空，请输入确认密码",Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!password.equals(passwordConfirm)) {
            Toast.makeText(context,"确认密码错误，请输入正确的确认密码",Toast.LENGTH_SHORT).show();
            return false;
        }

        if (UtilUser.userIsRegisterUser(phone,password,name)) {
            Toast.makeText(context,"该手机号已经注册，请输入其他手机号",Toast.LENGTH_SHORT).show();
            sResult = false;
            Log.d(TAG, "sResult: "+sResult);
            return false;
        }




        return true;
    }


    /**
     * 用户输入的手机号是否已经被注册
     */
    private static boolean sResult=false;//true,有相同手机号,已经注册。false,没有相同手机号,没有注册。
    public static boolean userIsRegisterUser(String phone,String password,String name) throws InterruptedException {


        UserBean userBean = UserBean.getUserBean();
        userBean.setTelephone(phone);
        userBean.setPassword(EncryptUtils.encryptMD5ToString(password));
        userBean.setName(name);

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        String s = gson.toJson(userBean);

        String mUrl = "http://192.168.0.107:8080/AndioStreamingService_war_exploded/";
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=GBK"), s);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mUrl + "isRegisterUser").post(requestBody).build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure ==> "+e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                sResult = Boolean.parseBoolean(string);
                Log.d(TAG, "onResponse: "+ sResult);
            }
        });
        Thread.sleep(500);//解决回调方法过慢
        Log.d(TAG, "userIsRegisterUser: "+sResult);

        return sResult;
    }



    public static void userIsRegisterUserAndIsPassword(String phone,String password) throws InterruptedException {

        UserBean userBean = UserBean.getUserBean();
        userBean.setTelephone(phone);
//        userBean.setPassword(EncryptUtils.encryptMD5ToString(password));
        userBean.setPassword(password);

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        String s = gson.toJson(userBean);

        String mUrl = "http://192.168.0.107:8080/AndioStreamingService_war_exploded/";
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=GBK"), s);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mUrl + "isRegisterUserAndIsPassword").post(requestBody).build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure ==> "+e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.d(TAG, "onResponse: "+string);
                Gson gson2 = new Gson();
                IsRegisterUserAndIsPasswordBean isRegisterUserAndIsPasswordBean = gson2.fromJson(string, IsRegisterUserAndIsPasswordBean.class);
                sIsPhone = isRegisterUserAndIsPasswordBean.isPhone();
                sIsPassword = isRegisterUserAndIsPasswordBean.isPassword();

                String name = isRegisterUserAndIsPasswordBean.getName();
                UserBean.getUserBean().setName(name);
                SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(UtilConstants.SP_NAME_USER, Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString(UtilConstants.SP_KEY_NAME, name);
                edit.commit();

                Log.d(TAG, "onResponse: "+ sIsPhone +","+ sIsPassword);
            }
        });
        Thread.sleep(500);//解决回调方法过慢

    }


    /**
     * 验证是否存在已登录用户
     */
    public static boolean validateIsUserLogin(Context context){
        return UtilSP.isLoginUser(context);
    }




    /**
     * 修改密码 的验证
     */
    public static boolean changePassword(Context context,String oldPassword, String password, String passwordConfirm){
        if (TextUtils.isEmpty(oldPassword)) {
            Toast.makeText(context,"原密码为空，请输入原密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(context,"新密码为空，请新输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(passwordConfirm)) {
            Toast.makeText(context,"确认密码为空，请输入确认密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!password.equals(passwordConfirm)) {
            Toast.makeText(context,"确认密码错误，请输入正确的确认密码",Toast.LENGTH_SHORT).show();
            return false;
        }

        //验证原密码是否正确
        if (!oldPassword.equals(UserBean.getUserBean().getPassword()))
        {
            Toast.makeText(context,"原密码错误，请输入正确的原密码",Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }






}

